import { useRef, useState } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, Col, Empty, FormInstance, Popconfirm, Row, Space, Table } from 'antd';

import Filter from '@/components/filter';
import SearchInput from '@/components/search-input';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { IdSort, TimeSort } from '@/enum';
import { dicInfoDelete, dicInfoList } from '@/services/base/jichumokuaizidianxinxijiekou';
import { dicMainDelete, dicMainPage } from '@/services/base/jichumokuaizidianzhuxinxijiekou';
import { Icon } from '@iconify/react/dist/iconify.js';

import Edit, { EditRef } from './edit';
import EditItem, { EditItemRef } from './edit-item';
import Import, { ImportRef } from './import';

export type BizObject = BASE.DicMain;

export type PageProps = {};

const Page: React.FC<PageProps> = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const editItem = useRef<EditItemRef>(null);
  const importRef = useRef<ImportRef>(null);
  const filter = useRef<FormInstance>();
  // 选择的字典
  const [selectedRow, setSelectedRow] = useState<BizObject>();
  const dictMain = useAntdTable(
    async ({ current, pageSize }, { id, ...formData } = {}) => {
      const res = await dicMainPage({
        ...formData,
        ...id,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序,
        idSort: IdSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter.current
    }
  );
  const dict = useRequest(
    async () => {
      if (!selectedRow) {
        return [];
      }

      return (
        await dicInfoList({
          code: selectedRow?.dicCode
        })
      ).data;
    },
    {
      refreshDeps: [selectedRow]
    }
  );

  const onSearch = () => {
    dictMain.search.submit();
  };

  const onReset = () => {
    dictMain.search.reset();
  };

  return (
    <>
      <Row gutter={[24, 24]}>
        <Col span={12}>
          {/* 筛选 */}
          <Filter
            onFinish={onSearch}
            formRef={filter}
            extra={
              <>
                {permission.check() && (
                  <Button
                    onClick={() => {
                      edit.current?.open({
                        type: 'add',
                        onSuccess: () => {
                          dictMain.refresh();
                        }
                      });
                    }}
                    icon={<Icon icon="ri:add-fill" />}
                  >
                    创建字典
                  </Button>
                )}
              </>
            }
          >
            <Filter.Item name="id">
              <SearchInput
                style={{
                  width: 120 * 3
                }}
                typeList={[
                  { value: 'username', children: '用户名' },
                  { value: 'id', children: '用户ID' }
                ]}
              />
            </Filter.Item>

            <Filter.Item>
              <Button htmlType="submit" disabled={dictMain.loading}>
                搜索
              </Button>
            </Filter.Item>

            <Filter.Item>
              <Button onClick={onReset} disabled={dictMain.loading}>
                重置
              </Button>
            </Filter.Item>
          </Filter>
          {/* end 筛选 */}

          <Table<BizObject>
            columns={[
              {
                title: '字典名称',
                dataIndex: 'dicName'
              },
              {
                title: '字典标识',
                dataIndex: 'dicCode'
              },
              {
                title: '字典值类型',
                dataIndex: 'valueType'
              },
              {
                title: '说明',
                dataIndex: 'dicExplain'
              },
              {
                title: '操作',
                fixed: 'right',
                align: 'center',
                render: (_, row) => {
                  return (
                    <Text.Space>
                      {permission.check() && (
                        <Text
                          onClick={() => {
                            edit.current?.open({
                              type: 'edit',
                              rowData: row,
                              onSuccess: () => {
                                dictMain.refresh();
                              }
                            });
                          }}
                          type="primary"
                        >
                          编辑
                        </Text>
                      )}

                      {permission.check() && (
                        <Popconfirm
                          title={`确定删除该字典吗？`}
                          onConfirm={async () => {
                            const res = await dicMainDelete({
                              id: row.id as unknown as string
                            });

                            store.app?.message.success(res.message);
                            dictMain.refresh();

                            return res.success;
                          }}
                        >
                          <Text type="danger">删除</Text>
                        </Popconfirm>
                      )}
                    </Text.Space>
                  );
                }
              }
            ]}
            scroll={{
              x: 'max-content'
            }}
            rowKey="id"
            bordered
            onRow={(row) => {
              return {
                onClick: () => {
                  setSelectedRow((prev) => (prev && prev.id === row.id ? undefined : row));
                }
              };
            }}
            {...dictMain.tableProps}
            pagination={{
              ...dictMain.tableProps.pagination
            }}
            size="small"
          />
        </Col>
        <Col span={12}>
          {!selectedRow ? (
            <Empty description="请选择字典" />
          ) : (
            <div>
              <Table<BASE.DicInfoVO>
                title={() => {
                  return (
                    <Space>
                      {permission.check() && (
                        <Button
                          onClick={() => {
                            editItem.current?.open({
                              type: 'add',
                              dicMain: selectedRow,
                              onSuccess: () => {
                                dict.refresh();
                              }
                            });
                          }}
                          icon={<Icon icon="ri:add-fill" />}
                        >
                          创建字典项
                        </Button>
                      )}

                      {permission.check() && (
                        <Button
                          onClick={() => {
                            importRef.current?.open({
                              rowData: selectedRow,
                              onSuccess: () => {
                                dict.refresh();
                              }
                            });
                          }}
                          icon={<Icon icon="ri:folder-upload-fill" />}
                        >
                          导入字典
                        </Button>
                      )}
                    </Space>
                  );
                }}
                dataSource={dict.data}
                size="small"
                bordered
                rowKey="id"
                scroll={{
                  x: 'max-content'
                }}
                columns={[
                  {
                    title: '字典名称',
                    dataIndex: 'dicName'
                  },
                  {
                    title: '字典值',
                    dataIndex: 'dicValue'
                  },
                  {
                    title: '状态',
                    dataIndex: 'dicStatus'
                  },
                  {
                    title: '字典颜色',
                    dataIndex: 'dicColour'
                  },
                  {
                    title: '字典图标',
                    dataIndex: 'dicIcon'
                  },
                  {
                    title: '排序',
                    dataIndex: 'dicSort'
                  },
                  {
                    title: '说明',
                    dataIndex: 'dicExplain'
                  },
                  {
                    title: '操作',
                    fixed: 'right',
                    align: 'center',
                    render: (_, row) => {
                      return (
                        <Text.Space>
                          {permission.check() && (
                            <Text
                              onClick={() => {
                                editItem.current?.open({
                                  type: 'edit',
                                  dicMain: selectedRow,
                                  rowData: row,
                                  onSuccess: () => {
                                    dict.refresh();
                                  }
                                });
                              }}
                              type="primary"
                            >
                              编辑
                            </Text>
                          )}

                          {permission.check() && (
                            <Popconfirm
                              title={`确定删除该字典吗？`}
                              onConfirm={async () => {
                                const res = await dicInfoDelete({
                                  id: row.id as unknown as string
                                });

                                store.app?.message.success(res.message);
                                dict.refresh();

                                return res.success;
                              }}
                            >
                              <Text type="danger">删除</Text>
                            </Popconfirm>
                          )}
                        </Text.Space>
                      );
                    }
                  }
                ]}
              />
            </div>
          )}
        </Col>
      </Row>

      <Edit ref={edit} />
      <EditItem ref={editItem} />
      <Import ref={importRef} />
    </>
  );
};

export default Page;
